package org.gangcai.mac.shop.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.CoordinatorLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextSwitcher;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewSwitcher;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.orhanobut.dialogplus.DialogPlus;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zaaach.citypicker.CityPicker;
import com.zaaach.citypicker.adapter.OnPickListener;
import com.zaaach.citypicker.model.City;
import com.zaaach.citypicker.model.HotCity;
import com.zaaach.citypicker.model.LocateState;
import com.zaaach.citypicker.model.LocatedCity;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import org.gangcai.mac.shop.activity.Animation1Activity;
import org.gangcai.mac.shop.activity.Animation2Activity;
import org.gangcai.mac.shop.activity.OrderActivity;
import org.gangcai.mac.shop.activity.TTShopDetailActivity;
import org.gangcai.mac.shop.adapter.AnimationAdapter;
import org.gangcai.mac.shop.bean.GoodInfoDetail;
import org.gangcai.mac.shop.bean.HomeArticleBaseBean;
import org.gangcai.mac.shop.bean.HomeMainDataBean;
import org.gangcai.mac.shop.bean.PostsArticleBaseBean;
import org.gangcai.mac.shop.bean.HomeDataBean;
import org.gangcai.mac.shop.bean.SlideBean;
import org.gangcai.mac.shop.holders.LocalImageHolderView;
import org.gangcai.mac.shop.manager.RetrofitManager;
import org.gangcai.mac.shop.manager.RetrofitManageres;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.gangcai.mac.shop.R;
import org.gangcai.mac.shop.activity.LoginActivity;
import org.gangcai.mac.shop.activity.MainActivity;
import org.gangcai.mac.shop.activity.SPProductListActivity;
import org.gangcai.mac.shop.activity.SPShopDetailActivity;
import org.gangcai.mac.shop.activity.ShopDetailActivity;
import org.gangcai.mac.shop.adapter.MultipleItemQuickAdapter;
import org.gangcai.mac.shop.adapter.PullToRefreshAdapter;
import org.gangcai.mac.shop.adapter.SectionAdapter;
import org.gangcai.mac.shop.api.AppAPI;
import org.gangcai.mac.shop.bean.CommonResonseBean;
import org.gangcai.mac.shop.bean.DataServer;
import org.gangcai.mac.shop.bean.HomeIndexBean;
import org.gangcai.mac.shop.bean.HomeIndexBean.HomeBean;
import org.gangcai.mac.shop.bean.HomeIndexBean.ShopCell;
import org.gangcai.mac.shop.bean.HomeIndexBean.Floor;
import org.gangcai.mac.shop.bean.IndexBean;
import org.gangcai.mac.shop.bean.MySection;
import org.gangcai.mac.shop.bean.RecommendBean;
import org.gangcai.mac.shop.bean.UpdateShopData;
import org.gangcai.mac.shop.constants.Constant;
import org.gangcai.mac.shop.entity.MultipleItem;
import org.gangcai.mac.shop.implement.MainTabItemListener;
import org.gangcai.mac.shop.loadmore.CustomLoadMoreView;
import org.gangcai.mac.shop.manager.RetrofitManagers;
import org.gangcai.mac.shop.oberver.CommonObserver;
import org.gangcai.mac.shop.rxlife.RxFragment;
import org.gangcai.mac.shop.utils.PromptDialogUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.android.schedulers.AndroidSchedulers;
import me.leefeng.promptlibrary.PromptDialog;

import static org.gangcai.mac.shop.constants.Constant.CODE_SUCC;
import static org.gangcai.mac.shop.entity.MultipleItem.IMG;
import static org.gangcai.mac.shop.entity.MultipleItem.IMG_TEXT;
import static org.gangcai.mac.shop.entity.MultipleItem.TEXT;

/**
 * 商品界面
 */
public class HomeFragment extends RxFragment implements OnRefreshListener ,View.OnClickListener {
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    Unbinder unbinder;
    ConvenientBanner convenientBanner;
    private List<String> newslist=new ArrayList<String>();
    private List<String> newslist1=new ArrayList<String>();
    private int index = 0;//textview上下滚动下标
    private int indexs = 0;//textview上下滚动下标
    public static final int NEWS_MESSAGE_TEXTVIEW = 100;//通知公告信息
    public static final int NEWS_MESSAGE_TEXTSEARCH = 101;//通知公告信息
    @BindView(R.id.btn_pick)
    TextView btn_pick;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    @BindView(R.id.textSwitcher)
    TextSwitcher textSwitcher;
    @BindView(R.id.main_content)
    CoordinatorLayout mainContent;
    ArrayList<PostsArticleBaseBean> datalist = new ArrayList<>();
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    private String mParam1;
    private String mParam2;
//    private CommonAdapter<PostsArticleBaseBean> adapter;
    private PromptDialog prompDialog;
    private AnimationAdapter animationAdapter;
    private static final int PAGE_SIZE = 6;
    private static final int MENU_SIZE = 10;
    private int mNextRequestPage = 1;
    private View headView;
    private View footView;
    TextSwitcher textSwitcher_search;
    private List<PostsArticleBaseBean> mainPostsList=new ArrayList<PostsArticleBaseBean>(  );

    private static MainTabItemListener mainTabItemListener;

    public HomeFragment() {
    }

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case NEWS_MESSAGE_TEXTVIEW:
                    index++;
                    textSwitcher.setText(newslist.get(index%newslist.size()));
                    if (index == newslist.size()) {
                        index = 0;
                    }
                    handler.sendEmptyMessageDelayed( NEWS_MESSAGE_TEXTVIEW ,4000);
                    break;
                case NEWS_MESSAGE_TEXTSEARCH:
                    indexs++;
                    textSwitcher_search.setText(newslist1.get(indexs%(newslist1.size()/2)*2)+"\n"+newslist1.get(indexs%(newslist1.size()/2)*2+1));
                    if (indexs == newslist1.size()/2) {
                        indexs = 0;
                    }
                    handler.sendEmptyMessageDelayed( NEWS_MESSAGE_TEXTSEARCH ,4000);
                    break;
                default:
                    break;
            }
        }
    };

    public static HomeFragment newInstance(MainTabItemListener mainTabItemListener1, String param1, String param2) {
        HomeFragment fragment = new HomeFragment();
        Bundle args = new Bundle();
        mainTabItemListener = mainTabItemListener1;
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
        EventBus.getDefault().register(this);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    private void setViewPagerData(List<String> data) {
        convenientBanner.setPages(
                new CBViewHolderCreator<LocalImageHolderView>() {
                    @Override
                    public LocalImageHolderView createHolder() {
                        return new LocalImageHolderView();
                    }
                }, data)
                //设置两个点图片作为翻页指示器，不设置则没有指示器，可以根据自己需求自行配合自己的指示器,不需要圆点指示器可用不设
                .setPageIndicator(new int[]{R.mipmap.indicator_normal, R.mipmap.indicator_focus})
                //设置指示器的方向
                .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.CENTER_HORIZONTAL);
        convenientBanner.startTurning(5000);
        convenientBanner.setScrollDuration(3000);
        try {
            Class<?> clazz = Class.forName("com.bigkoo.convenientbanner.ConvenientBanner");
            Field loPageTurningPoint = clazz.getDeclaredField("loPageTurningPoint");
            loPageTurningPoint.setAccessible(true);
            ViewGroup o = (ViewGroup) loPageTurningPoint.get(convenientBanner);
            RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) o.getLayoutParams();
            layoutParams.bottomMargin = SizeUtils.dp2px(12);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        prompDialog = PromptDialogUtils.getPrompDialog(getActivity());
        headView = getLayoutInflater().inflate(R.layout.home_head_view, (ViewGroup) recyclerview.getParent(), false);
        footView = getLayoutInflater().inflate(R.layout.home_foot_view, (ViewGroup) recyclerview.getParent(), false);
        convenientBanner=(ConvenientBanner)headView.findViewById(R.id.convenientBanner);
        textSwitcher_search=(TextSwitcher) headView.findViewById(R.id.textSwitcher_search);
        RetrofitManageres.getInstance().create(AppAPI.class).Slide("Api","Slide","listJson","2")
                .observeOn(AndroidSchedulers.mainThread())
                .compose(this.<SlideBean>bindToLifecycle())
                .subscribe(new CommonObserver<SlideBean>(refreshLayout) {
                    @Override
                    public void onSuccess(SlideBean value) {
                        if (value.getCode() == CODE_SUCC) {
                            ArrayList<String> viewpageDatas = new ArrayList<>();
                            for(int i=0;i<value.getReferer().size();i++) {
                                viewpageDatas.add( Constant.IMAGE_PATH + value.getReferer().get(i).getSlide_pic() );
                            }
                            setViewPagerData(viewpageDatas);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        Toast.makeText(getActivity(), R.string.network_err, Toast.LENGTH_LONG).show();
                    }
                });
        initAdapter();
        loadData();
        int layout_id=R.id.layout_01;
        for(int i=0;i<MENU_SIZE;i++){
            LinearLayout linearLayout=(LinearLayout)headView.findViewById(layout_id+i);
            linearLayout.setOnClickListener( this );
        }
        newsMessage();
        newsMessageSearch();
        textSwitcher.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle extras = new Bundle();
                extras.putString("cat_id", "5");
                extras.putString("titleString", "城库交易资讯");
//                Toast.makeText(getActivity(),newslist.get(index),Toast.LENGTH_SHORT).show();
                ActivityUtils.startActivity( extras, Animation2Activity.class);
            }
        });
        textSwitcher_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Toast.makeText(getActivity(),newslist1.get(indexs*2),Toast.LENGTH_SHORT).show();
                ActivityUtils.startActivity( getActivity(), OrderActivity.class);
            }
        });

        btn_pick.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CityPicker.from(getActivity())
                        .enableAnimation(false)
                        .setAnimationStyle(R.style.DefaultCityPickerAnimation)
                        .setLocatedCity(null)
                        .setHotCities(null)
                        .setOnPickListener(new OnPickListener() {
                            @Override
                            public void onPick(int position, City data) {
                                btn_pick.setText(String.format("%s", data.getName()));
//                                Toast.makeText(
//                                        getActivity(),
//                                        String.format("点击的数据：%s，%s", data.getName(), data.getCode()),
//                                        Toast.LENGTH_SHORT)
//                                        .show();
                            }

                            @Override
                            public void onCancel() {
                                Toast.makeText(getActivity(), "取消选择", Toast.LENGTH_SHORT).show();
                            }

                            @Override
                            public void onLocate() {
                                //开始定位，这里模拟一下定位
                                new Handler().postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        CityPicker.from(getActivity()).locateComplete(new LocatedCity("上海市", "上海市", "121100"), LocateState.SUCCESS);
                                    }
                                }, 3000);
                            }
                        })
                        .show();
            }
        });

    }

    private void refreshMainView() {
        RetrofitManageres.getInstance().create(AppAPI.class).HomeData("Portal","list","indexJson","3")
                .observeOn(AndroidSchedulers.mainThread())
                .compose(this.<HomeDataBean>bindToLifecycle())
                .subscribe(new CommonObserver<HomeDataBean>(refreshLayout) {
                    @Override
                    public void onSuccess(HomeDataBean value) {
                        if (value.getCode() == Constant.CODE_SUCC) {
                            mainPostsList=value.getReferer().getPosts();
                            animationAdapter.setNewData(mainPostsList);
                            animationAdapter.loadMoreComplete();
                        }
                    }
                });
    }

    private void newsMessage() {
        textSwitcher.setFactory(new ViewSwitcher.ViewFactory() {
            @Override
            public View makeView() {
                TextView textView = new TextView(getActivity());
                textView.setSingleLine();
                textView.setTextSize(16);//字号
                textView.setText( "城库货源最新新闻信息" );
                textView.setTextColor( Color.parseColor("#f7f7f7"));
                textView.setEllipsize( TextUtils.TruncateAt.END);
                FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                        ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                params.gravity = Gravity.CENTER;
                textView.setLayoutParams(params);
                return textView;
            }
        });
//        handler.sendEmptyMessageDelayed( NEWS_MESSAGE_TEXTVIEW ,4000);
    }

    private void newsMessageSearch() {
        textSwitcher_search.setFactory(new ViewSwitcher.ViewFactory() {
            @Override
            public View makeView() {
                TextView textView = new TextView(getActivity());
                textView.setLines(2);
                textView.setTextSize(15);//字号
                textView.setLineSpacing(8,1);
                textView.setText("城库找车获取您需要的最新车资讯\n城库货源为您提供最近的货运信息" );
                textView.setEllipsize( TextUtils.TruncateAt.END);
                FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                        ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                params.gravity = Gravity.CENTER_VERTICAL;
                textView.setLayoutParams(params);
                return textView;
            }
        });
//        handler.sendEmptyMessageDelayed( NEWS_MESSAGE_TEXTSEARCH ,4000);
    }

    private void initAdapter() {
        refreshLayout.setEnableLoadmore(false);
        refreshLayout.setEnableRefresh(true);
        refreshLayout.setOnRefreshListener(this);
        animationAdapter = new AnimationAdapter(getActivity(),mainPostsList);
        animationAdapter.openLoadAnimation();
        animationAdapter.setNotDoAnimationCount(3);
        recyclerview.setLayoutManager(new GridLayoutManager(getActivity(), 1));
        animationAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {

            }
        });
        animationAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                PostsArticleBaseBean postsArticleBaseBean=mainPostsList.get( position );
                Bundle bundle = new Bundle();
                bundle.putString( "tid",postsArticleBaseBean.getTid() );
                bundle.putString( "term_id",postsArticleBaseBean.getTerm_id() );
                bundle.putString( "post_id",postsArticleBaseBean.getObject_id() );
                bundle.putString( "post_title",postsArticleBaseBean.getPost_title() );
                bundle.putString( "post_authorname",postsArticleBaseBean.getPost_authorname() );
                bundle.putString( "mobile",postsArticleBaseBean.getMobile() );
                bundle.putString( "post_area",postsArticleBaseBean.getPost_area() );
                bundle.putString( "post_price",postsArticleBaseBean.getPost_price() );
                bundle.putString( "post_date",postsArticleBaseBean.getPost_date() );
                bundle.putString( "photos_urls",postsArticleBaseBean.getPhotos_urls() );
                bundle.putString( "photos_content",postsArticleBaseBean.getPost_excerpt() );
                ActivityUtils.startActivity(bundle, getActivity(), TTShopDetailActivity.class);
            }
        });
        animationAdapter.addHeaderView(headView);
        recyclerview.setAdapter(animationAdapter);
        animationAdapter.loadMoreComplete();
    }

    private void showCartsDialog() {
        final DialogPlus dialog = DialogPlus.newDialog( getActivity() )
                .setGravity( Gravity.CENTER )
                .setContentBackgroundResource( android.R.color.transparent )
                .setContentWidth( ViewGroup.LayoutParams.WRAP_CONTENT )  // or any custom width ie: 300
                .setContentHeight( ViewGroup.LayoutParams.WRAP_CONTENT )
                .setContentHolder( new com.orhanobut.dialogplus.ViewHolder( R.layout.cartscreate_dialog_layout ) )
                .setExpanded( false )  // This will enable the expand feature, (similar to android L share dialog)
                .create();
        View holderView = dialog.getHolderView();
        holderView.findViewById( R.id.mcart_confirm_btn1 ).setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        } );
        holderView.findViewById( R.id.mcart_confirm_btn2 ).setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mainTabItemListener!=null){
                    mainTabItemListener.onMainTabItemListener(3);
                }
                dialog.dismiss();
            }
        } );

        dialog.show();


    }

    private void loadData() {
        LogUtils.e("loadHomeFragment");
        mNextRequestPage = 1;
        RetrofitManageres.getInstance().create(AppAPI.class).HomeMainData("Portal","list","indexHomeJson")
                .observeOn(AndroidSchedulers.mainThread())
                .compose(this.<HomeMainDataBean>bindToLifecycle())
                .subscribe(new CommonObserver<HomeMainDataBean>(refreshLayout) {
                    @Override
                    public void onSuccess(HomeMainDataBean value) {
                        if (value.getCode() == CODE_SUCC) {
                            mainPostsList=value.getReferer().getLists3().getPosts();
                            List<PostsArticleBaseBean> getPosts1=value.getReferer().getLists1().getPosts();
                            List<PostsArticleBaseBean> getPosts2=value.getReferer().getLists2().getPosts();
                            List<PostsArticleBaseBean> getPosts5=value.getReferer().getLists5().getPosts();
                            if(getPosts1.size()>0){
                                newslist1=new ArrayList<String>();
                                for(PostsArticleBaseBean bean:getPosts1){
                                    String titleString=bean.getPost_title();
                                    if(titleString.length()>24){
                                        titleString = titleString.substring(0, 24);
                                    }
                                    newslist1.add(titleString);
                                }
                            }
                            if(getPosts2.size()>0){
                                for(PostsArticleBaseBean bean:getPosts2){
                                    String titleString=bean.getPost_title();
                                    if(titleString.length()>24){
                                        titleString = titleString.substring(0, 24);
                                    }
                                    newslist1.add(titleString);
                                }
                                handler.sendEmptyMessageDelayed( NEWS_MESSAGE_TEXTSEARCH ,4000);
                            }
                            if(getPosts5.size()>0){
                                newslist=new ArrayList<String>();
                                for(PostsArticleBaseBean bean:getPosts5){
                                    newslist.add(bean.getPost_title());
                                }
                                handler.sendEmptyMessageDelayed( NEWS_MESSAGE_TEXTVIEW ,4000);
                            }
                            animationAdapter.setNewData(mainPostsList);
                            animationAdapter.loadMoreComplete();
                        }
                    }

                });

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe
    public void onEvent(UpdateShopData data) {
//        loadData();
    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        refreshMainView();
    }

    @Override
    public void onClick(View view) {
        String catIDString;
        String titleString;
        switch (view.getId()) {
            case R.id.layout_01:
                catIDString = "7";
                titleString = "城库板材报价";
                break;
            case R.id.layout_02:
                catIDString = "8";
                titleString = "城库型材报价";
                break;
            case R.id.layout_03:
                catIDString = "9";
                titleString = "城库管材报价";
                break;
            case R.id.layout_04:
                catIDString = "10";
                titleString = "城库建材报价";
                break;
            case R.id.layout_05:
                catIDString = "11";
                titleString = "城库废钢报价";
                break;
            case R.id.layout_06:
                catIDString = "12";
                titleString = "城库钢结构报价";
                break;
            case R.id.layout_07:
                catIDString = "13";
                titleString = "城库原料报价";
                break;
            case R.id.layout_08:
                catIDString = "14";
                titleString = "城库工程机械报价";
                break;
            case R.id.layout_09:
                catIDString = "15";
                titleString = "城库其他货源报价";
                break;
                default:
                    catIDString = "7";
                    titleString = "城库板材报价";
                    break;
        }
        Bundle extras = new Bundle();
        extras.putString("cat_id", catIDString);
        extras.putString("titleString", titleString);
        ActivityUtils.startActivity( extras, Animation2Activity.class);
    }

}
